package com.medical.blood.controller;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
import com.medical.blood.entity.PaymentOrder;
import com.medical.blood.service.PaymentOrderService;
import com.medical.blood.service.WxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private PaymentOrderService orderService;
    @Autowired
    private WxPayService wxPayService;
    @Autowired
    private WxPayService wxPayServiceSDK; // 微信支付SDK服务

    /**
     * 生成订单并获取微信支付参数（小程序调用）
     */
    @PostMapping("/create")
    public Map<String, Object> createOrder(
            @RequestParam Long userId,
            @RequestParam String deviceId,
            @RequestParam String testItemIds,
            @RequestParam BigDecimal totalAmount,
            @RequestParam String openid) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 1. 生成订单
            PaymentOrder order = orderService.createOrder(userId, deviceId, testItemIds, totalAmount);
            // 2. 调用微信支付统一下单接口（金额转换为分）
            int totalFee = totalAmount.multiply(new BigDecimal(100)).intValue();
            String notifyUrl = "https://你的域名/order/wxpay/notify"; // 回调地址
            var wxPayResult = wxPayService.createWxPayOrder(order.getOrderNo(), totalFee, openid, notifyUrl);
            // 3. 返回订单号及支付参数
            result.put("orderNo", order.getOrderNo());
            result.put("payParams", wxPayResult);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 微信支付回调接口（支付平台调用）
     */
    @PostMapping("/wxpay/notify")
    public String handleWxPayNotify(@RequestBody String xmlData) {
        try {
            // 1. 解析微信支付回调数据
            WxPayOrderNotifyResult notifyResult = wxPayServiceSDK.parseOrderNotifyResult(xmlData);
            String orderNo = notifyResult.getOutTradeNo(); // 商户订单号
            String transactionId = notifyResult.getTransactionId(); // 微信交易号
            // 2. 更新订单支付状态
            boolean success = orderService.updatePayStatus(orderNo, transactionId);
            return success ? "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>"
                    : "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[处理失败]]></return_msg></xml>";
        } catch (Exception e) {
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[" + e.getMessage() + "]]></return_msg></xml>";
        }
    }

    /**
     * 查询订单状态（小程序调用）
     */
    @GetMapping("/status")
    public Map<String, Object> getOrderStatus(@RequestParam String orderNo, @RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            String status = orderService.getOrderStatus(orderNo, userId);
            result.put("status", status);
            result.put("success", true);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }
}
